package com.zscat.mallplus.center.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.center.entity.CenterInviteRecords;
import com.zscat.mallplus.center.entity.CenterVerification;
import com.zscat.mallplus.center.mapper.CenterVerificationMapper;
import com.zscat.mallplus.center.service.CenterService;
import com.zscat.mallplus.center.service.ICenterJifenService;
import com.zscat.mallplus.center.service.ICenterVerificationService;
import com.zscat.mallplus.center.vo.MemberInfoVo;
import com.zscat.mallplus.cms.entity.CmsSubject;
import com.zscat.mallplus.cms.entity.CmsSubjectComment;
import com.zscat.mallplus.cms.mapper.CmsSubjectMapper;
import com.zscat.mallplus.cms.service.ICmsSubjectCommentService;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.oms.entity.OmsOrder;
import com.zscat.mallplus.oms.entity.OmsOrderItemTicket;
import com.zscat.mallplus.oms.entity.OmsOrderReturnApply;
import com.zscat.mallplus.oms.service.IOmsOrderItemTicketService;
import com.zscat.mallplus.oms.service.IOmsOrderReturnApplyService;
import com.zscat.mallplus.oms.service.IOmsOrderService;
import com.zscat.mallplus.pms.entity.PmsProduct;
import com.zscat.mallplus.pms.mapper.PmsProductMapper;
import com.zscat.mallplus.sys.entity.AdminDayStatics;
import com.zscat.mallplus.sys.entity.SysStore;
import com.zscat.mallplus.sys.entity.SysUser;
import com.zscat.mallplus.sys.mapper.SysStoreMapper;
import com.zscat.mallplus.sys.service.IAdminDayStaticsService;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.util.UserUtils;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.DateUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
//@Api(tags = "CenterController", description = "个人中心")
//@RequestMapping("/api/center")
@RequestMapping("/centers")

public class CenterControllers {
	@Resource
	private IUmsMemberService memberService;
	@Resource
	private CenterService centerService;
	@Resource
	private CenterVerificationMapper verificationMapper;
	@Resource
	private ICenterJifenService centerJifenService;
	@Resource
	private IAdminDayStaticsService adminDayStaticsService;
	@Resource
	private ICmsSubjectCommentService subjectCommentService;
	@Resource
	private ICenterVerificationService verificationService;
	@Resource
	private IOmsOrderItemTicketService orderItemTicketService;
	@Resource
	private IOmsOrderService orderService;
	@Autowired
	private SysStoreMapper storeMapper;
	@Autowired
	private PmsProductMapper productMapper;
	@Autowired
	private CmsSubjectMapper subjectMapper;
	@Autowired
	private IOmsOrderReturnApplyService orderReturnApplyService;

	/**
	 * 添加邀请
	 * 
	 * @param centerInviteRecords
	 * @return
	 */
	@PostMapping("/invite/add")
	public Object addInviteData(@RequestBody CenterInviteRecords centerInviteRecords) {
		CenterInviteRecords inviteRecords = centerService.getInviteRecordsByInviteId(centerInviteRecords.getInviteId());
		if (inviteRecords != null) {
			return new CommonResult().failed("已绑定推荐人");
		}
		// 被邀请人（注册用户）
		UmsMember umsMember = memberService.getById(centerInviteRecords.getInviteId());
		// 邀请人
		UmsMember member = memberService.getById(centerInviteRecords.getUserId());
		umsMember.setInvite(member.getId());
		umsMember.setInviteName(member.getNickname());
		memberService.updateById(umsMember);
		return new CommonResult().success(centerService.addInviteData(centerInviteRecords));
	}

	/**
	 * 我的邀请
	 * 
	 * @param userId
	 * @return
	 */
//	@IgnoreAuth
//    @SysLog(MODULE = "center", REMARK = "我的邀请")
	@GetMapping("/invite/{userId}")
	public Object getInviteData(@PathVariable("userId") Long userId) {
		return new CommonResult().success(centerService.getInviteData(userId));
	}

	/**
	 * 我的推广
	 * 
	 * @param userId
	 * @return
	 */
//	@IgnoreAuth
//  @SysLog(MODULE = "center", REMARK = "我的推广")
//	@GetMapping("/extend/{userId}")
//	public Object getExtendData(@PathVariable("userId") Long userId) {
//		return new CommonResult().success(centerService.getExtendData(userId));
//	}

	// TODO
	/**
	 * 我的消息
	 * 
	 * @param userId
	 * @return
	 */
//	@IgnoreAuth
//  @SysLog(MODULE = "center", REMARK = "我的推广")
	@GetMapping("/message/{userId}")
	public Object getMessageData(@PathVariable("userId") Long userId) {
		return new CommonResult().success(centerService.getMessageData(userId));
	}

//	/**
//	 * 添加系统消息
//	 * 
//	 * @param adminSysNotice
//	 * @return
//	 */
//	@PostMapping("/message/adminSysNotice/add")
//	public Object addAdminSysNotice(@RequestBody AdminSysNotice adminSysNotice) {
//		return new CommonResult().success(centerService.addAdminSysNotice(adminSysNotice));
//	}

	/**
	 * 系统消息列表addAdminSysNotice
	 * 
	 * @param userId
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/user/{userId}")
	public Object getAdminSysNoticeList(@PathVariable("userId") Long userId) {
		return new CommonResult().success(centerService.getAdminSysNoticeList(userId));
	}

	/**
	 * 系统消息详情
	 * 
	 * @param userId
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/{noticeId}")
	public Object getAdminSysNotice(@PathVariable("noticeId") Long noticeId) {
		return new CommonResult().success(centerService.getAdminSysNotice(noticeId));
	}

	/**
	 * 实名认证
	 * 
	 * @param userId
	 * @return
	 */
//	@IgnoreAuth
//  @SysLog(MODULE = "center", REMARK = "实名认证")
//	@PostMapping("/identification/add")
//	public Object addIdentification(@RequestBody CenterIdentification centerIdentification) {
//		//审核通过
//		if() {
//			return new CommonResult().failed("审核通过不可修改");
//		}
//		return new CommonResult().success(centerService.addIdentification(centerIdentification));
//	}

	/**
	 * 获取实名认证信息
	 * 
	 * @param userId
	 * @return
	 */
//	@IgnoreAuth
//  @SysLog(MODULE = "center", REMARK = "实名认证")
//	@GetMapping("/identification/{userId}")
//	public Object getIdentificationData(@PathVariable("userId") Long userId) {
//		return new CommonResult().success(centerService.getIdentificationData(userId));
//	}

	/*
	 * 获取所有个人信息-喜欢的分类
	 * 
	 * @return
	 */
	@GetMapping("/memberInfo/getMemberTags")
	public Object getMemberTagsData() {
		return new CommonResult().success(centerService.getMemberTagsData());
	}

	/**
	 * 修改个人信息
	 * 
	 * @param userId
	 * @return
	 */
//	@IgnoreAuth
//  @SysLog(MODULE = "center", REMARK = "修改个人信息")
	@PostMapping("/memberInfo/update")
	public Object updateMemberInfo(@RequestBody MemberInfoVo memberInfoVo) {
		if (memberInfoVo.getUserId() == null) {
			return new CommonResult().failed("用户信息异常");
		}
		return new CommonResult().success(centerService.updateMemberInfo(memberInfoVo));
	}

	/**
	 * 获取个人信息
	 * 
	 * @param userId
	 * @return
	 */
//	@IgnoreAuth
//  @SysLog(MODULE = "center", REMARK = "获取个人信息")
	@GetMapping("/memberInfo/{userId}")
	public Object getMemberInfoData(@PathVariable("userId") Long userId) {
		return new CommonResult().success(centerService.getMemberInfoData(userId));
	}

	// 新增核销码（支付成功后回调）
	/**
	 * @param orderSn 订单号
	 * @return
	 */
	@GetMapping("/verification/add")
	public Object addVerification(@RequestParam(required = true, name = "orderSn") String orderSn) {
		// 订单是否已生成核销码
		Integer orderCount = verificationMapper
				.selectCount(new QueryWrapper<CenterVerification>().eq("order_sn", orderSn));
		if (orderCount.compareTo(0) > 0) {
			return new CommonResult().success();
		}
		return new CommonResult().success(centerService.addVerification(orderSn));
	}

	/**
	 * 管理页核销码列表
	 * 
	 */
	@GetMapping("/verification/list")
	public Object listVerification(CenterVerification entity,
			@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
		return new CommonResult().success(verificationService.page(new Page<CenterVerification>(pageNum, pageSize),
				new QueryWrapper<>(entity).orderByDesc("create_time")));
	}

	/**
	 * 批量核销
	 * 
	 */
	@GetMapping("/verification/update")
	public Object updateVerification(String ids) {
		Long orderId = null;
		SysUser user = UserUtils.getCurrentMember();
		String[] str = ids.split(",");
		CenterVerification ver = new CenterVerification();
		ver.setOperateId(user.getId());
		ver.setOperateName(user.getNickName());
		ver.setUpdateTime(new Date());
		ver.setVerification(1);
		for (String string : str) {
			ver.setId(Long.valueOf(string));
			verificationMapper.updateById(ver);
			CenterVerification verification = verificationMapper.selectById(Long.valueOf(string));
			if (orderId == null) {
				orderId = verification.getOrderId();
			}
			OmsOrderItemTicket ticket = orderItemTicketService.getOne(
					new QueryWrapper<OmsOrderItemTicket>().eq("coupon_code", verification.getVerificationCode()));
			ticket.setStatus(1);
			orderItemTicketService.updateById(ticket);
			List<OmsOrderItemTicket> list = orderItemTicketService
					.list(new QueryWrapper<OmsOrderItemTicket>().eq("order_id", orderId).eq("status", 0));
			if (list == null || list.size() == 0) {
				OmsOrder entity = new OmsOrder();
				entity.setId(orderId);
				entity.setStatus(3);
				entity.setConfirmStatus(1);
				entity.setReceiveTime(new Date());
				orderService.updateById(entity);
			}
		}
		
		return new CommonResult().success();
	}

	/**
	 * 系统通知获取会员详情
	 * 
	 * @param noticeId
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/getMemberList/{noticeId}")
	public Object getMemberList(@PathVariable(name = "noticeId") Long noticeId) {
		return new CommonResult().success(centerService.getAdminSysNoticeMemberList(noticeId));
	}

	/**
	 * 获取所有会员
	 * 
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/getAllMemberList")
	public Object getAllMemberList() {
		return new CommonResult().success(centerService.getAllMemberList());
	}

	/**
	 * 新增系统通知
	 * 
	 * @param userIds
	 * @param noticeId
	 * @return
	 */
	@GetMapping("/message/adminSysNotice/add")
	public Object addCenterUserSysNotice(@RequestParam(name = "userIds") Long[] userIds,
			@RequestParam(name = "noticeId") Long noticeId) {
		return new CommonResult().success(centerService.addCenterUserSysNotice(userIds, noticeId));
	}

//	/**
//	 * 商户统计
//	 * @param entity
//	 * @param pageNum
//	 * @param pageSize
//	 * @return
//	 */
//	@GetMapping(value = "/adminStatic/list")
//	public Object getAdminAllStaticsByPage(AdminDayStatics entity,
//			@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
//			@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
//		try {
//			return new CommonResult().success(adminDayStaticsService.page(new Page<AdminDayStatics>(pageNum, pageSize),
//					new QueryWrapper<>(entity).select(
//							"store_id,store_name,SUM(IFNULL(goods_count,0)) AS allGoodsCount,SUM(IFNULL(article_count,0)) AS allArticleCount,SUM(IFNULL(pay_order_count,0)) AS allPayOrderCount,SUM(IFNULL(pay_amount,0)) AS allPayAmount,SUM(IFNULL(not_pay_order_count,0)) AS allNotPayOrderCount,SUM(IFNULL(not_pay_amount,0)) AS allNotPayAmount")
//							.groupBy("store_id").groupBy("store_name")));
//		} catch (Exception e) {
//			log.error("根据条件查询所有商户统计列表：%s", e.getMessage(), e);
//		}
//		return new CommonResult().failed();
//	}

	/**
	 * 商户统计
	 * 
	 * @param entity
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@GetMapping(value = "/adminStatic/list")
	public Object getAdminAllStaticsByPage(AdminDayStatics entity,
			@RequestParam(name = "status", required = false) Integer status,
			@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
		try {
			SysStore sysStore = new SysStore();
			sysStore.setName(entity.getStoreName());
			sysStore.setStatus(3);
			IPage<SysStore> selectPage = storeMapper.selectPage(new Page<SysStore>(pageNum, pageSize),
					new QueryWrapper<SysStore>(sysStore));
			List<AdminDayStatics> list = new ArrayList<AdminDayStatics>();
			for (SysStore store : selectPage.getRecords()) {
				List<PmsProduct> productList = productMapper
						.selectList(new QueryWrapper<PmsProduct>().eq("store_id", store.getId()));
				List<OmsOrder> orderList = orderService
						.list(new QueryWrapper<OmsOrder>().eq("store_id", store.getId()).ne("order_type", 4).eq("status", 3));

				AdminDayStatics dayStatics = new AdminDayStatics();
				dayStatics.setAllGoodsCount(productList.size());
				// dayStatics.setMemberCount(memberList.size());

				Integer payOrderCount = 0;
				BigDecimal payAmount = BigDecimal.ZERO;
				Integer notPayOrderCount = 0;
				BigDecimal notPayAmount = BigDecimal.ZERO;
				for (OmsOrder omsOrder : orderList) {
					if (omsOrder.getPayAmount() != null) {
						if (null == status) {
							payOrderCount++;
							payAmount = payAmount.add(omsOrder.getPayAmount());
						} else if (omsOrder.getStatus() == status) {
							payOrderCount++;
							payAmount = payAmount.add(omsOrder.getPayAmount());
						}
						if (omsOrder.getStatus() == OrderStatus.REFUND.getValue()) {
							notPayOrderCount++;
							notPayAmount = notPayAmount.add(omsOrder.getPayAmount());
						}
					}
				}
				dayStatics.setAllPayAmount(payAmount);
				dayStatics.setAllPayOrderCount(payOrderCount);
				dayStatics.setAllNotPayAmount(notPayAmount);
				dayStatics.setAllNotPayOrderCount(notPayOrderCount);
				dayStatics.setStoreId(store.getId());
				dayStatics.setStoreName(store.getName());
				dayStatics.setCreateTime(DateUtils.addDays(new Date(), -1));
				
				//退款统计
				Integer allRefundCount = 0;
				BigDecimal allRefundAmount = BigDecimal.ZERO;
				List<OmsOrderReturnApply> orderReturnApplyList = orderReturnApplyService.list(new QueryWrapper<OmsOrderReturnApply>().eq("store_id", store.getId()).eq("status",2));
				for (OmsOrderReturnApply orderReturnApply : orderReturnApplyList) {
					allRefundCount++;
					allRefundAmount= allRefundAmount.add(orderReturnApply.getReturnAmount());
				}
				dayStatics.setAllRefundCount(allRefundCount);
				dayStatics.setAllRefundAmount(allRefundAmount);

				// 文章统计
				List<CmsSubject> subjectList = subjectMapper
						.selectList(new QueryWrapper<CmsSubject>().eq("store_id", store.getId()));
				dayStatics.setAllArticleCount(subjectList.size());
				list.add(dayStatics);
			}
			return new CommonResult().success(new IPage<AdminDayStatics>() {
				private static final long serialVersionUID = 1L;

				@Override
				public List<AdminDayStatics> getRecords() {
					return list;
				}

				@Override
				public IPage<AdminDayStatics> setRecords(List<AdminDayStatics> records) {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public long getTotal() {
					// TODO Auto-generated method stub
					return selectPage.getTotal();
				}

				@Override
				public IPage<AdminDayStatics> setTotal(long total) {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public long getSize() {
					// TODO Auto-generated method stub
					return 0;
				}

				@Override
				public IPage<AdminDayStatics> setSize(long size) {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public long getCurrent() {
					// TODO Auto-generated method stub
					return 0;
				}

				@Override
				public IPage<AdminDayStatics> setCurrent(long current) {
					// TODO Auto-generated method stub
					return null;
				}
			});
		} catch (Exception e) {
			log.error("根据条件查询所有商户统计列表：%s", e.getMessage(), e);
		}
		return new CommonResult().failed();
	}

	/**
	 * 后台添加回复
	 * 
	 * @param entity
	 * @return
	 */
	@PostMapping(value = "/subjectComment/update/{id}")
	public Object updateCmsSubjectComment(@RequestBody CmsSubjectComment entity) {
		try {
			CmsSubjectComment subjectComment = subjectCommentService.getById(entity.getId());
			if (null == subjectComment) {
				return new CommonResult().failed("评论编号有误");
			}
			if (null != subjectComment.getReplyTime()) {
				return new CommonResult().failed("后台仅可回复用户评论一次");
			}
			entity.setReplyTime(new Date());
			if (subjectCommentService.updateById(entity)) {
				return new CommonResult().success();
			}
		} catch (Exception e) {
			log.error("更新专题评论表：%s", e.getMessage(), e);
			return new CommonResult().failed();
		}
		return new CommonResult().failed();
	}
}
